<template>
  <div class="group-list">
    <!-- 顶部标题与按钮在一行 -->
    <div class="header" style="display: flex; justify-content: space-between; align-items: center;">
      <h2 class="title" style="margin: 0; font-size: 20px;">群聊列表</h2>
      <el-button 
        plain 
        size="small" 
        @click="showDialog = true"
        style="font-size: 12px;"
      >
        + 新建群聊
      </el-button>
    </div>

    <ul>
      <li
        v-for="group in groups"
        :key="group.id"
        class="group-item"
        @click="selectChat(group)"
      >
        <img :src="group.avatar" alt="群头像" class="group-avatar" />
        <div class="group-info">
          <div class="group-name">{{ group.groupName }}</div>
          <div class="group-desc">{{ group.description }}</div>
        </div>
      </li>
    </ul>

    <!-- 创建群聊弹窗 - 两列布局 -->
    <el-dialog 
      v-model="showDialog" 
      title="选择联系人" 
      width="600px"
      :show-close="false"
      custom-class="custom-group-dialog"
    >
      <div class="dialog-content">
        <!-- 左侧好友列表 -->
        <div class="left-column">
          <el-input 
            v-model="searchText" 
            placeholder="搜索" 
            style="margin-bottom: 15px;"
            clearable
          />
          
          <div class="friend-list">
            <div 
              v-for="friend in filteredFriends" 
              :key="friend.id"
              class="friend-item"
              @click="toggleSelect(friend)"
            >
              <div class="friend-select" :class="{ selected: isSelected(friend) }">
                <el-icon v-if="isSelected(friend)"><Check /></el-icon>
              </div>
              <img :src="friend.avatar || 'default-avatar.png'" class="friend-avatar" />
              <div class="friend-name">{{ friend.remark || friend.friendId }}</div>
            </div>
          </div>
        </div>

        <!-- 右侧已选列表 -->
        <div class="right-column">
          <el-input
            v-model="newGroupName"
            placeholder="请输入群聊名称（可选）"
            show-word-limit
            style="margin-bottom: 15px;"
          />
          <div class="selected-title">已选联系人</div>
          <div class="selected-list">
            <div 
              v-for="friend in selectedFriends" 
              :key="friend.id"
              class="selected-item"
            >
              <img :src="friend.avatar || 'default-avatar.png'" class="selected-avatar" />
              <span>{{ friend.friendId }}</span>
            </div>
          </div>
          
          <div class="action-buttons">
           <!-- 在模板部分修改取消按钮 -->
            <el-button @click="handleCancel" size="small">取消</el-button>
            <el-button 
              type="primary" 
              @click="createGroup" 
              size="small"
              :disabled="selectedFriends.length === 0"
            >
              完成
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import request from '@/axios/index.js'
import {useFriendStore} from '@/stores/friendStore'

const router = useRouter()
const groups = ref([])
const friendStore = useFriendStore();
const friends = computed(()=>friendStore.friends)
const username = ref()

const showDialog = ref(false)
const newGroupName = ref('')
const selectedFriends = ref([])
const searchText = ref('')

// 计算属性过滤好友列表
const filteredFriends = computed(() => {
  return friends.value.filter(friend => {
    const name = (friend.remark || friend.friendId).toLowerCase()
    return name.includes(searchText.value.toLowerCase())
  })
})

// 检查好友是否被选中
const isSelected = (friend) => {
  return selectedFriends.value.some(f => f.friendId === friend.friendId)
}

// 切换好友选择状态
const toggleSelect = (friend) => {
  const index = selectedFriends.value.findIndex(f => f.friendId === friend.friendId)
  if (index > -1) {
    selectedFriends.value.splice(index, 1)
  } else {
    selectedFriends.value.push(friend)
  }
}

const fetchGroups = (username) => {
  request.get('/group/all/' + username.value).then((res) => {
    groups.value = res
  }).catch((err) => {
    console.error("获取群聊失败", err)
  })
}

const getFriends = ()=>{
  request.get('/friend/all',{}).then((res)=>{
    console.log("好友列表获取成功",res);
    const cur = [];
    res.forEach(element => {
        if(element.friendId == username.value){
          cur.push({
            id: Date.now().toString(),
            name:element.userId,
            avatar: 'https://picsum.photos/200/200',
            friendId:element.userId,
            remark:element.userId,
          })
        }else{
          cur.push({
            id: Date.now().toString(),
            name:element.friendId,
            avatar: 'https://picsum.photos/200/200',
            friendId:element.friendId,
            remark:element.friendId,
          })
        }
    });
    friendStore.changeFriends(cur);
    // friends.value = cur;    
    console.log("friends：",friends.value);
  })
  .catch((err) => {
      console.error("好友获取失败:", err);
  });
}

const selectChat = (group) => {
  router.push({ path: '/group', query: { groupId: group.groupId, groupName: group.groupName, createBy: group.createBy } })
}

const createGroup = () => {
  if (selectedFriends.value.length === 0) {
    ElMessage.warning("请选择要添加的好友")
    return
  }

  const payload = {
    groupName: newGroupName.value.trim() || `群聊(${selectedFriends.value.length + 1})`, // 若为空则用默认名
    members: selectedFriends.value.map(f => f.username),
    createBy: username.value
  }

  request.post('/group/create', payload).then(res => {
    ElMessage.success("群聊创建成功")
    showDialog.value = false
    selectedFriends.value = []
    searchText.value = ''
    newGroupName.value = ''
    fetchGroups(username)
  }).catch(err => {
    console.error("创建群聊失败", err)
    ElMessage.error("群聊创建失败")
  })
}
// 在 script setup 部分添加 handleCancel 方法
const handleCancel = () => {
  selectedFriends.value = []
  newGroupName.value = ''
  showDialog.value = false
}


onMounted(() => {
  window.electronAPI.getUsername().then((res) => {
    username.value = res
    fetchGroups(username)
    getFriends();
  })
})
</script>

<style scoped>
.group-list {
  padding: 20px;
}
.title {
  font-size: 18px;
  margin-bottom: 10px;
}
ul {
  list-style: none;
  padding: 0;
}
.group-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background 0.2s;
}
.group-item:hover {
  background: #f5f5f5;
}
.group-avatar {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  margin-right: 10px;
}
.group-info {
  display: flex;
  flex-direction: column;
}
.group-name {
  font-weight: bold;
}
.group-desc {
  font-size: 12px;
  color: #888;
}

/* 弹窗内容样式 */
.dialog-content {
  display: flex;
  height: 400px;
}

.left-column {
  flex: 1;
  padding-right: 20px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.right-column {
  width: 200px;
  padding-left: 20px;
  display: flex;
  flex-direction: column;
}

.friend-list {
  flex: 1;
  overflow-y: auto;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}
.friend-item:hover {
  background-color: #f5f5f5;
}
.friend-select {
  width: 20px;
  height: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.friend-select.selected {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}
.friend-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
}
.friend-name {
  flex: 1;
}

/* 右侧已选列表样式 */
.selected-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}
.selected-list {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 每行3个头像 */
  gap: 8px; /* 头像间距 */
  align-content: flex-start;
}

.selected-item {
  display: flex;
  justify-content: center;
  align-items: center;
}


.selected-avatar {
  width: 50px; /* 调整头像大小 */
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}
.selected-name {
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}
</style>

<style>
.custom-group-dialog .el-dialog__header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  margin-right: 0;
}
.custom-group-dialog .el-dialog__body {
  padding: 15px 20px;
}
</style>